import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xiaomi/app/modules/tools/httpClient.dart';
import '../../../models/goodsDetailModel.dart';

class GoodsDetailController extends GetxController {
  //TODO: Implement GoodsDetailController
  ScrollController scrollController = ScrollController();
  RxDouble opa = (0.0).obs;

  List titles = [
    {'id': 1, 'title': '商品'},
    {'id': 2, 'title': '列表'},
    {'id': 3, 'title': '详情'},
  ];
  RxInt currentIndex = 1.obs;
  RxBool isHidden = false.obs;

  GlobalKey k1 = GlobalKey();
  GlobalKey k2 = GlobalKey();
  GlobalKey k3 = GlobalKey();

  final goodlistmodel = GoodDetailItemModel().obs;

  // RxList<GoodsAttrModel> goodAttrmodel = <GoodsAttrModel>[].obs;

  @override
  void onInit() {
    super.onInit();

    scrollController.addListener(() {
      if (scrollController.position.pixels > 0 &&
          scrollController.position.pixels <=
              kToolbarHeight + Get.statusBarHeight) {
        opa.value = scrollController.position.pixels /
            (kToolbarHeight + Get.statusBarHeight);
        print(opa.value);
        isHidden.value = true;

        update();
      } else if (scrollController.position.pixels >
          kToolbarHeight + Get.statusBarHeight) {
        isHidden.value = false;
        update();
      }
    });

    // 获取详情页数据
    _getData();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  setCurrentIndex(int index) {
    currentIndex.value = index;
    update();
  }

  _getData() async {
    String url = 'api/pcontent?id=${Get.arguments['id']}';
    var rsp = await HttpClient.get(url);
    print(rsp);
    if (rsp != null) {
      goodlistmodel.value = GoodDetailsModel.fromJson(rsp.data).result!;

      // /// 本地修改一下数据格式
      // goodAttrmodel.value = goodlistmodel.value.attr!;
      setupModel();
      update();
    }
  }

  updateAttrModel(cate, listItem) {
    print(cate);
    print(listItem);
    for (var i = 0; i < goodlistmodel.value.attr!.length; i++) {
      // 表示选中的一级标题与当前相同
      if (goodlistmodel.value.attr![i].cate == cate) {
        for (var j = 0; j < goodlistmodel.value.attr![i].listMap!.length; j++) {
          goodlistmodel.value.attr![i].listMap![j]['selected'] = false;
          if (goodlistmodel.value.attr![i].listMap![j]['title'] ==
              listItem['title']) {
            goodlistmodel.value.attr![i].listMap![j]['selected'] = true;
          }
        }
      }
    }

    print(goodlistmodel.value.attr);
    update();
  }

  void setupModel() {
    for (var i = 0; i < goodlistmodel.value.attr!.length; i++) {
      for (var j = 0; j < goodlistmodel.value.attr![i].list!.length; j++) {
        goodlistmodel.value.attr![i].listMap?.add({
          'title': goodlistmodel.value.attr![i].list![j],
          'selected': false
        });
      }
    }
  }
}
